package cn.chiship.framework.docs.biz.controller;


import cn.chiship.framework.common.constants.CommonConstants;
import cn.chiship.framework.docs.biz.service.DocsCacheService;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.encryption.Md5Util;
import cn.chiship.sdk.core.enums.HeaderEnum;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.util.ServletUtil;
import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.docs.biz.pojo.dto.FileCatalogConfigDto;

import cn.chiship.framework.docs.biz.entity.FileCatalogConfig;
import cn.chiship.framework.docs.biz.entity.FileCatalogConfigExample;
import cn.chiship.framework.docs.biz.service.FileCatalogConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * controller
 *
 * @author lijian
 * @date 2020/4/23
 */
@RestController
@Authorization
@RequestMapping("/catalog")
@Api(tags = "文档目录")
public class FileCatalogConfigController extends BaseController<FileCatalogConfig, FileCatalogConfigExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileCatalogConfigController.class);

    @Resource
    private FileCatalogConfigService fileCatalogConfigService;
    @Resource
    DocsCacheService cacheService;

    @Override
    public BaseService getService() {
        return fileCatalogConfigService;
    }


    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, systemName = CommonConstants.SYSTEM_NAME_DOCS, describe = "根据AppId初始化文件目录结构")
    @ApiOperation(value = "根据AppId初始化文件目录结构")
    @GetMapping(value = "/initCatalog")
    public ResponseEntity<BaseResult> initCatalog() {
        return super.responseEntity(fileCatalogConfigService.initCatalog(ServletUtil.getHeader(HeaderEnum.HEADER_PROJECTS_ID.getName())));
    }

    @ApiOperation(value = "加载系统文件目录")
    @GetMapping(value = "/listSystemCatalog")
    public ResponseEntity<BaseResult> listSystemCatalog() {
        FileCatalogConfigExample fileCatalogConfigExample = new FileCatalogConfigExample();
        /**
         * 创造条件
         */
        fileCatalogConfigExample.createCriteria()
                .andIsDeletedEqualTo(BaseConstants.NO)
                .andCatalogPidEqualTo("0")
                .andCatalogTypeEqualTo(Byte.valueOf("9"))
                .andProjectsIdEqualTo(ServletUtil.getHeader(HeaderEnum.HEADER_PROJECTS_ID.getName()));
        /**
         * 排序
         */
        fileCatalogConfigExample.setOrderByClause("orders asc,is_built_in desc,gmt_modified desc");
        List<FileCatalogConfig> fileCatalogConfigs = fileCatalogConfigService.selectByExample(fileCatalogConfigExample);
        return super.responseEntity(BaseResult.ok(fileCatalogConfigs));
    }

    @ApiOperation(value = "加载当前文件目录下得文档目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid", value = "所属文件夹", defaultValue = "", required = true, dataTypeClass = String.class, paramType = "query")
    })
    @GetMapping(value = "/listByPid")
    public ResponseEntity<BaseResult> listByPid(
            @RequestParam(value = "pid") String pid) {
        cacheService.cacheFileCatalog();
        FileCatalogConfigExample fileCatalogConfigExample = new FileCatalogConfigExample();
        /**
         * 创造条件
         */
        fileCatalogConfigExample.createCriteria()
                .andIsDeletedEqualTo(BaseConstants.NO)
                .andCatalogPidEqualTo(pid)
                .andProjectsIdEqualTo(ServletUtil.getHeader(HeaderEnum.HEADER_PROJECTS_ID.getName()));
        /**
         * 排序
         */
        fileCatalogConfigExample.setOrderByClause("orders asc,is_built_in desc,gmt_modified desc");
        List<FileCatalogConfig> fileCatalogConfigs = fileCatalogConfigService.selectByExample(fileCatalogConfigExample);
        return super.responseEntity(BaseResult.ok(fileCatalogConfigs));
    }

    @SystemOptionAnnotation(describe = "验证文件夹密码")
    @ApiOperation(value = "验证文件夹密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path", required = true)
    })
    @PostMapping(value = "checkPassword/{id}")
    public ResponseEntity<BaseResult> checkPassword(@PathVariable("id") String id,
                                                    @RequestBody String password) {
        FileCatalogConfig fileCatalogConfig = fileCatalogConfigService.selectByPrimaryKey(id);

        FileCatalogConfigExample fileCatalogConfigExample = new FileCatalogConfigExample();
        fileCatalogConfigExample.createCriteria()
                .andIsDeletedEqualTo(BaseConstants.NO)
                .andIdEqualTo(id).andEncryptionPasswordEqualTo(Md5Util.md5(password + fileCatalogConfig.getEncryptionSalt()));

        List<FileCatalogConfig> fileCatalogConfigList = fileCatalogConfigService.selectByExample(fileCatalogConfigExample);
        if (fileCatalogConfigList.isEmpty()) {
            return super.responseEntity(BaseResult.error("密码错误"));
        }
        return super.responseEntity(BaseResult.ok(true));
    }

    @SystemOptionAnnotation(describe = "删除文档目录")
    @ApiOperation(value = "删除文档目录")
    @GetMapping(value = "remove/{id}")
    public ResponseEntity<BaseResult> remove(@PathVariable("id") String id) {
        CacheUserVO cacheUserVO = getLoginUser();
        return super.responseEntity(
                fileCatalogConfigService.updatePidByIdList(
                        id,
                        cacheUserVO.getId().toString(),
                        cacheUserVO.getUsername(),
                        cacheUserVO.getRealName()),
                HttpStatus.OK
        );
    }

    @ApiOperation(value = "保存文档目录")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid FileCatalogConfigDto fileCatalogConfigDto) {
        CacheUserVO cacheUserVO = getLoginUser();
        FileCatalogConfig fileCatalogConfig = new FileCatalogConfig();
        BeanUtils.copyProperties(fileCatalogConfigDto, fileCatalogConfig);
        fileCatalogConfig.setUserId(cacheUserVO.getId().toString());
        fileCatalogConfig.setUserName(cacheUserVO.getUsername());
        fileCatalogConfig.setRealName(cacheUserVO.getRealName());
        fileCatalogConfig.setProjectsId(ServletUtil.getHeader(HeaderEnum.HEADER_PROJECTS_ID.getName()));
        return super.responseEntity(fileCatalogConfigService.insertSelective(fileCatalogConfig));
    }


    @ApiOperation(value = "文件夹重命名")
    @PostMapping(value = "updateCatalogNameById/{id}")
    public ResponseEntity<BaseResult> updateCatalogNameById(@PathVariable("id") String id,
                                                            @RequestBody FileCatalogConfigDto fileCatalogConfigDto) {
        CacheUserVO cacheUserVO = getLoginUser();
        FileCatalogConfig fileCatalogConfig = new FileCatalogConfig();
        BeanUtils.copyProperties(fileCatalogConfigDto, fileCatalogConfig);
        fileCatalogConfig.setId(id);
        return super.responseEntity(fileCatalogConfigService.updateCatalogNameById(
                fileCatalogConfig, cacheUserVO.getId().toString(), cacheUserVO.getUsername(), cacheUserVO.getRealName()),
                HttpStatus.OK);
    }


}
